<?php
/**
 * 更改用户上级 弃用  用数据表单的形式做
 * Created by PhpStorm.
 * User: eric
 * Date: 2020/7/23
 * Time: 17:31
 */

namespace App\Admin\Extensions\Action;


use App\Exceptions\ServiceException;
use App\Exceptions\ServiceExceptionConstant;
use App\Models\Message;
use App\Models\Users;
use App\Models\UserScoreRecord;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AddUserScoreAction extends RowAction
{
    public $name = '更新积分';

    protected $selector = '.add-user-score';

    public function handle(Model $model, Request $request)
    {
        $qty    = $request->input('qty');
        $type   = (int)$request->input('op_type');
        $remark = $request->input('remark') ?? '';
        if (empty($remark)) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('请填写备注'));
        }
        if (empty($qty) || !is_numeric($qty) || intval($qty) <= 0) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('改动数量异常'));
        }

        DB::beginTransaction();
        //处理逻辑
        try {
            if ($type == 0) {
                //增加用户积分
                Users::where('id', $model->id)->increment('score', $qty);
            }
            if ($type == 1) {
                //积分减少
                $rel = Users::where('id', $model->id)->where('score', '>=', $qty)->decrement('score', $qty);
                if (!$rel) {
                    throw new ServiceException(ServiceExceptionConstant::getErrorData('积分不足'));
                }
            }
            $newQty = $type == 0 ? $qty : -$qty;
            UserScoreRecord::create(['user_id' => $model->id, 'qty' => $newQty, 'buss_type' => 4, 'remark' => $remark]);
            Message::create(['user_id' => $model->id, 'title' => '积分变动提醒', 'content' => $remark . $qty . '积分']);
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->response()->error($exception->getMessage())->refresh();
        }
        return $this->response()->success('更新成功')->refresh();
    }

    public function form()
    {
        $this->text('qty', '数量')->required()->help("增减积分数量")->value(1);
        $this->radio('op_type', '类型')->options(['增加', '减少']);
        $this->text('remark', '备注')->default('参加公益');
    }

    public function html()
    {
        return "<a class='add-user-score btn btn-sm btn-success'><i class='fa fa-plus'></i></a>";
    }

}
